/**
 * @description: 定义班级 service
 * @version: 0.0.1
 * @author: z..
 * @Date: 2023-06-12 18:16:39
 */

import { Provide } from '@midwayjs/core';
import { UserRoleRecords } from './user_role_records.entity';

import { InjectRepository, InjectDataSource } from '@midwayjs/sequelize';
import { Repository, Sequelize } from 'sequelize-typescript';

@Provide()
export class UserRoleRecordsModel {

  @InjectRepository(UserRoleRecords)
  UserRoleRecordsRepository: Repository<UserRoleRecords>;

  @InjectDataSource()
  SequelizeQuery: Sequelize;

  /**
   * 查询角色编码是否存在
   * @returns 
   */
  async getCountByCode(role_code: string): Promise<any> {
    return await this.UserRoleRecordsRepository.count(
      {
        where: { role_code }
      }
    );
  };

  /**
   * 新增角色信息
   * @returns 
   */
  async createdUserRole(role_name: string, role_code: string): Promise<any> {
    return await this.UserRoleRecordsRepository.create(
      {
        role_name: role_name,
        role_code: role_code,
        created_at: new Date(),
        updated_at: new Date()
      }
    );
  };

  /**
   * 根据id更新角色信息
   * @param id 
   * @param role_name 
   * @param role_code 
   * @returns 
   */
  async updateUserRole(id: number, role_name: string, role_code: string): Promise<any> {
    return await this.UserRoleRecordsRepository.update(
      {
        role_name: role_name,
        role_code: role_code,
        updated_at: new Date()
      },
      {
        where: {
          id: id
        }
      }
    );
  };

  /**
   * 根据id删除角色信息
   * @param id 
   * @returns 
   */
  async delUserRole(id: number): Promise<any> {
    return await this.UserRoleRecordsRepository.destroy({
      where: {
        id: id
      }
    });
  };

  /**
   * 分页查询获取列表
   * @param {*} pageNum 
   * @param {*} pageSize
   * @returns 
   */
  async getUserRoleList(pageNum: number, pageSize: number): Promise<any> {
    const offset = (pageNum - 1) * pageSize;

    const { count, rows } = await this.UserRoleRecordsRepository.findAndCountAll({
      offset: offset,
      limit: pageSize,
      order: [['created_at', 'DESC']] // 可选：根据需要排序
    });
    return {
      currentPage: pageNum,
      totalPages: Math.ceil(count / pageSize),
      totalItems: count,
      items: rows
    };
  }

}